// pages/house-detail/house-detail.js
import req from "../../../utils/request"
Page({
  data: {
    houseId: "",
    statusText: "已通过",
    statusClass: "status-approved",
    setting: false,
    showSetDefaultButton: true,

    // 房屋信息初始化为空
    houseInfo: {
      community: "",
      room: "",
      area: ""
    },

    // 住户信息初始化为空
    residentInfo: {
      photo: "", 
      name: "",
      phone: "",
      idType: "",
      idNumber: "",
      residentType: "",
      tagName: ""
    }
  },

  onLoad(options) {
    if (options.id) {
      const houseId = options.id;
      this.setData({ houseId });
      this.fetchHouseDetail(houseId);
      this.checkShowDefaultButton();
    } else {
      console.error("缺少房屋ID参数");
      wx.showToast({ title: "参数错误", icon: "none" });
    }
  },

  // 获取房屋详情
  fetchHouseDetail(id) {
    wx.showLoading({ title: "加载中..." });
    
    // 模拟API请求 - 使用实际数据
    setTimeout(async () => {
      // 直接使用您提供的JSON数据作为响应
      const response = await req.get(`/property/house/${id}`)
      
      if (response.code === 200 && response.data) {
        this.processHouseData(response.data);
      } else {
        wx.showToast({ 
          title: response.msg || "数据加载失败", 
          icon: "none" 
        });
      }
      
      wx.hideLoading();
    }, 500);
  },

  // 处理房屋数据
  processHouseData(apiData) {
    // 1. 房屋信息处理
    const houseInfo = {
      community: apiData.communityName || "未知小区",
      room: `${apiData.buildingName || "未知楼栋"} ${apiData.unitName || "未知单元"} ${apiData.floor || "未知楼层"} ${apiData.doorNumber || "未知门号"}`,
      area: apiData.area ? `${apiData.area} m²` : "未知面积"
    };
    
    // 2. 住户信息处理
    let residentInfo = {
      photo: "",
      name: "无住户信息",
      phone: "",
      idType: "",
      idNumber: "",
      residentType: "",
      tagName: ""
    };
    
    if (apiData.owner) {
      residentInfo = {
        photo: apiData.owner.image || "/images/default-avatar.png", // 默认头像路径
        name: apiData.owner.name || "未知姓名",
        phone: this.maskPhone(apiData.owner.phone), // 手机号脱敏处理
        idType: apiData.owner.idTypeName || "未知证件类型",
        idNumber: this.maskIdNumber(apiData.owner.idNumber), // 身份证号脱敏处理
        residentType: apiData.owner.typeName || "未知类型",
        tagName: apiData.owner.tagName || "" // 用户标签
      };
    }
    
    // 3. 状态处理
    const statusMap = {
      0: { text: "已通过", class: "status-approved" },
      1: { text: "待审核", class: "status-pending" },
      2: { text: "已驳回", class: "status-rejected" }
    };
    
    const statusInfo = statusMap[apiData.status] || statusMap[1];
    
    // 4. 更新数据
    this.setData({
      houseInfo,
      residentInfo,
      statusText: statusInfo.text,
      statusClass: statusInfo.class
    });
    
    console.log("房屋详情数据:", this.data);
  },

  // 手机号脱敏处理
  maskPhone(phone) {
    if (!phone || phone.length < 7) return phone || "";
    return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
  },

  // 身份证号脱敏处理
  maskIdNumber(idNumber) {
    if (!idNumber || idNumber.length < 15) return idNumber || "";
    return idNumber.replace(/(\d{6})\d{8}(\w{4})/, "$1********$2");
  },

  // 检查是否显示设为默认按钮
  checkShowDefaultButton() {
    const defaultHouseId = wx.getStorageSync("defaultHouseId");
    this.setData({
      showSetDefaultButton: defaultHouseId !== this.data.houseId
    });
  },

  // 设为默认房屋
  onSetDefault() {
    wx.showModal({
      title: "提示",
      content: "确定要将该房屋设为默认吗？",
      success: (res) => {
        if (res.confirm) {
          this.handleSetDefault();
        }
      },
    });
  },

  // 处理设为默认
  handleSetDefault() {
    this.setData({ setting: true });

    // 模拟API请求
    setTimeout(() => {
      // 实际项目中这里应该是API请求
      wx.setStorageSync("defaultHouseId", this.data.houseId);
      
      this.setData({
        setting: false,
        showSetDefaultButton: false,
      });
      
      wx.showToast({ title: "设置成功", icon: "success" });
      
      // 通知上级页面刷新
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      if (prevPage && prevPage.loadHouses) {
        prevPage.loadHouses();
      }
    }, 1000);
  },

  // 预览住户照片
  onPreviewPhoto() {
    const { photo } = this.data.residentInfo;
    if (!photo || photo.includes("default-avatar")) {
      wx.showToast({ title: "暂无照片", icon: "none" });
      return;
    }
    
    wx.previewImage({
      current: photo,
      urls: [photo],
    });
  },
});